<?php
/**
 * 上货管理
 * edition ：v1
 * create time：2021-06-08
 * author: acker
 */
namespace App\Admin\Controllers\Goods;


use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\NetworkCreditRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\NetworkGoodsOrderDetailModel;
use App\Models\yb\NetworkGoodsOrderModel;
use App\Models\yb\GoodsTypeModel;
use Encore\Admin\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;



class LoadingController extends Controller
{
    use ModelForm;

    protected $header = '上货管理';

    /**
     * 工作状态列表
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('列表');
            $content->body($this->grid());

        });
    }

    /**
     * 新增
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('添加');
            $content->body($this->form());

        });
    }

    /**
     * @return mixed
     */
    public function form(){

        $form = new Form(new NetworkGoodsOrderModel());

        $form->table('goods_list','上货', function ($table) {
            $table->select('goods_id','商品')->options(GoodsModel::selectOptions());
            $table->text('number','数量');
        });

        $form->select('network_id','网点')->options(AdminUserModel::selectOptions())->required();

        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
        });

        //保存前回调
        $form->saved(function (Form $form) {

            $user_data = AdminUserModel::where(['id'=> $form->model()->network_id])->first();

            $goods_list_data = $form->model()->goods_list;

            $goods_list = [];

            $orderSn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            $network_goods_order = array();
            //商品总价
            $goods_total_amount = 0;
            //商品抵扣数
            $credit_deduction = 0;
            //商品抵扣金额
            $credit_deduction_amount = 0;
            //桶押金
            $total_barrel_deposit = 0;
            //桶押金抵扣
            $total_barrel_deposit_deduction = 0;
            //桶押金抵扣数
            $total_barrel_deposit_deduction_number = 0;
            //配送费抵扣
            $distribution_fee_deduction = 0;

            DB::beginTransaction();

            foreach($goods_list_data as $key=>$val){
                $goods_list[$key]['goods_id'] = $val['goods_id'];
                $goods_list[$key]['number'] = $val['number'];
                $goods_data = GoodsModel::where(['status'=>1,'id'=>$val['goods_id']])->first();
                if(empty($goods_data)){
                    return response()->json(['code' => '201', 'msg' => $goods_data['goods_title']."已下架或库存不足"]);
                }
                $goods_list[$key]['goods_title'] = $goods_data['goods_title'];
                $goods_data_arrar[] = $goods_data;
                //桶押金
                $detail_barrel_deposit = $val['number']*$goods_data['barrel_deposit'];

                $network_goods = NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->select(['return_credit','barrel_deposit'])->first();
                //商品抵扣数
                if($network_goods['return_credit']>$val['number']){
                    $return_credit = $val['number'];
                }else{
                    $return_credit = $network_goods['return_credit'];
                }

                //扣除商品信用
                if($return_credit>0){
                    NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->decrement('return_credit',$return_credit);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $user_data['id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $return_credit,
                        'amount' => $return_credit*$goods_data['retail_goods_price'],
                        'remark' => '上货信用抵扣',
                        'status' => 0,
                        'relation_data' => $orderSn,
                        'type' => 1,
                        'created_at' => date('Y-m-D H:i:s',time())
                    ]);
                }

                //桶押金抵扣数
                if($network_goods['barrel_deposit']>$val['number']){
                    $barrel_deposit_number = $val['number'];
                }else{
                    $barrel_deposit_number = $network_goods['barrel_deposit'];
                }
                //扣除桶押金
                if($barrel_deposit_number>0){
                    NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->decrement('barrel_deposit',$barrel_deposit_number);
                    NetworkCreditRecordModel::insert([
                        'network_id' => $user_data['id'],
                        'goods_id'=> $val['goods_id'],
                        'number' => $barrel_deposit_number,
                        'amount' => $barrel_deposit_number*$goods_data['barrel_deposit'],
                        'remark' => '上货桶押金抵扣',
                        'status' => 0,
                        'relation_data' => $orderSn,
                        'type' => 5,
                        'created_at' => date('Y-m-D H:i:s',time())
                    ]);
                }

                $network_goods_order[$key] = [
                    'order_sn' => $orderSn,
                    'network_id' => $user_data['id'],
                    'goods_id' => $val['goods_id'],
                    'goods_title' => $goods_data['goods_title'],
                    'goods_price' => $goods_data['retail_goods_price'],
                    'number' => $val['number'],
                    'goods_total_amount' => $val['number']*$goods_data['retail_goods_price'],
                    'credit_deduction' => $return_credit,
                    'credit_deduction_amount' => $return_credit*$goods_data['retail_goods_price'],
                    'barrel_deposit' => $detail_barrel_deposit,
                    'barrel_deposit_number' => $barrel_deposit_number,
                    'barrel_deposit_deduction' => $barrel_deposit_number*$goods_data['barrel_deposit'],
                    'created_at' => date('Y-m-d H:i:s',time())
                ];

                //商品抵扣数
                $credit_deduction = $credit_deduction+$return_credit;
                //商品抵扣金额
                $credit_deduction_amount = $credit_deduction_amount+$return_credit*$goods_data['retail_goods_price'];
                //桶押金抵扣数
                $total_barrel_deposit_deduction_number = $total_barrel_deposit_deduction_number+$barrel_deposit_number;
                //桶押金抵扣金额
                $total_barrel_deposit_deduction = $total_barrel_deposit_deduction+$barrel_deposit_number*$goods_data['barrel_deposit'];
                //桶总押金
                $total_barrel_deposit = $total_barrel_deposit+$val['number']*$goods_data['barrel_deposit'];
                //商品总价
                $goods_total_amount = $goods_total_amount+$goods_data['retail_goods_price']*$val['number'];

            }
            //总价
            $total_amount = $goods_total_amount+$total_barrel_deposit;
            //商品抵扣后金额
            $amount = $total_amount-$credit_deduction_amount-$total_barrel_deposit_deduction;

            $distribution_price = 0;

            //计算减去配送费后实际需要支付
            if($user_data['distribution_price']>0 && $amount>0){
                if($amount>$user_data['distribution_price']){
                    $amount = $amount-$user_data['distribution_price'];
                    $distribution_price = $user_data['distribution_price'];
                }else{
                    $amount = 0;
                    $distribution_price = $amount;
                }
                //扣除配送费
                AdminUserModel::where(['id' => Admin::user()->id])->decrement('distribution_price',$distribution_price);

                NetworkCreditRecordModel::insert([
                    'network_id' => $user_data['id'],
                    'amount' => $distribution_price,
                    'remark' => '上货配送费抵扣',
                    'status' => 0,
                    'relation_data' => $orderSn,
                    'type' => 3,
                    'created_at' => date('Y-m-D H:i:s',time())
                ]);
            }

            //添加订单
            NetworkGoodsOrderModel::where(['id'=>$form->model()->id])->update([
                'order_sn' => $orderSn,
                'network_id' => $user_data['id'],
                'openid' => $user_data['openid'],
                'goods_list' => json_encode($goods_list),
                'total_amount' => $total_amount,
                'credit_deduction' => $credit_deduction,
                'credit_deduction_amount' => $credit_deduction_amount,
                'barrel_deposit' => $total_barrel_deposit,
                'barrel_deposit_deduction' => $total_barrel_deposit_deduction,
                'barrel_deposit_deduction_number' => $total_barrel_deposit_deduction_number,
                'distribution_fee_deduction'=> $distribution_price,
                'amount' => $amount,
                'status' => 1,
                'goods_total_amount' => $goods_total_amount,
                'created_at' => date('Y-m-d H:i:s',time())
            ]);
            //添加订单详情
            NetworkGoodsOrderDetailModel::insert($network_goods_order);

            Db::commit();

        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
        });

        return $form;
    }

    /**
     * 编辑
     * @return Content
     */
    public function show($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $order_data = NetworkGoodsOrderModel::where(['id'=>$id])->first();

            if($order_data['status'] == 0){
                $order_data['status'] = "待支付";
            }elseif($order_data['status'] == 1){
                $order_data['status'] = "待审核";
            }elseif($order_data['status'] == 2){
                $order_data['status'] = "审核不通过";
            }elseif($order_data['status'] == 3){
                $order_data['status'] = "带配送";
            }elseif($order_data['status'] == 4){
                $order_data['status'] = "已完成";
            }elseif($order_data['status'] == 5){
                $order_data['status'] = "已取消";
            }

            $network_data = AdminUserModel::where(['id'=>$order_data['network_id']])->first();

            $order_detail_data = NetworkGoodsOrderDetailModel::where(['order_sn'=>$order_data['order_sn']])->get();
            foreach($order_detail_data as $key=>$val){
                $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->first();
                $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
                $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
                $order_detail_data[$key]['goods_data'] = $goods_data;
            }

            $content->header($this->header);
            $content->description('详情');
            $content->body(view('admin.order.loading_order_detail',[
                'network_data' => $network_data,
                'order_data' => $order_data,
                'order_detail_data' => $order_detail_data
            ]));

        });
    }

    public function grid(){

        $grid = new Grid(new NetworkGoodsOrderModel());
        if(Admin::user()->id == 1){
            $grid->model()->orderBy('created_at', 'DESC');
        }else{
            $grid->model()->where(['network_id'=>Admin::user()->id])->orderBy('created_at', 'DESC');
        }

        $grid->column('order_sn','订单编号')->display(function($filed){
            return empty($filed) ? config('view.EmptyData') : $filed;
        });

        $grid->column('goods_total_amount','商品总额')->display(function($filed){
            return empty($filed) ? 0 : "¥".$filed;
        });

        $grid->column('barrel_deposit','桶押金总额')->display(function($filed){
            return empty($filed) ?  0 : "¥".$filed;
        });

        $grid->column('total_amount','订单总金额')->display(function($filed){
            return empty($filed) ? 0 : "¥".$filed;
        });

        $grid->column('credit_deduction_amount','信用抵扣')->display(function($filed){
            return empty($filed) ?  0 : "¥".$filed;
        });

        $grid->column('barrel_deposit_deduction','桶押金抵扣')->display(function($filed){
            return empty($filed) ?  0 : "¥".$filed;
        });

        $grid->column('distribution_fee_deduction','配送费抵扣')->display(function($filed){
            return empty($filed) ?  0 : "¥".$filed;
        });

        $grid->column('amount','实付金额')->display(function($filed){
            return empty($filed) ?  0 : "¥".$filed;
        });

        $grid->column('status','订单状态')->using([
            '0' => '待支付',
            '1' => '待审核',
            '2' => '审核不通过',
            '3' => '待配送',
            '4' => '已完成',
            '5' => '已取消'
        ], '未知')->dot([
            0 => 'danger',
            1 => 'info',
            2 => 'warning',
            3 => 'primary',
            4 => 'success',
            4 => 'danger',
        ], 'success');

        $grid->column('created_at','下单时间')->display(function($filed){
            return empty($filed) ? config('view.EmptyData') : $filed;
        })->sortable();

        //搜索
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->like('order_sn','订单号');
                $filter->between('created_at', '下单时间')->datetime();
            });
            $filter->column(1/2, function ($filter) {
                $filter->like('Network.name','下单网点');
                $filter->equal('status', '状态')->select([
                    '0' => '待支付',
                    '1' => '待审核',
                    '2' => '审核不通过',
                    '3' => '待配送',
                    '4' => '已完成',
                    '5' => '已取消'
                ]);
            });
            $filter->disableIdFilter();
        });

        $grid->fixColumns(1, -1);

        $grid->actions(function($actions){
            $actions->disableDelete();
            $actions->disableEdit();
        });

        $grid->disableExport();

        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });

        $grid->paginate(10);

        return $grid;
    }


}
